package com.sylar.happyreader.page;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.net.Uri;
import android.text.TextUtils;

import com.sylar.happyreader.ReadBookActivity;
import com.sylar.happyreader.net.HttpTool;
import com.sylar.happyreader.tools.Config;
import com.sylar.happyreader.tools.Utils;

public class BookPageFactory implements Runnable{
	private ArrayList<ArrayList<String>> lists = new ArrayList<ArrayList<String>>();
	
	private int m_mbBufLen = 0;  
	private int m_mbBufBegin = 0;
	private Bitmap m_book_bg = null;
	private int mWidth;
	private int mHeight;

	private List<String> m_lines = new ArrayList<String>();

	private int m_fontSize = 30;
	private int m_textColor = Color.BLACK;
	private int m_backColor = 0xffff9e85; 
	private int marginWidth = 15; 
	private int marginHeight = 20; 

	private int mLineCount; 
	private float mVisibleHeight; 
	private float mVisibleWidth; 
	private boolean m_isfirstPage, m_islastPage;
	private String msex;
	private String mstyle;
	private String mbookName;

	private Paint mPaint;
	
	private Context mContext;
	
	private int line = -1 ;
	//#E6D5AB
	public BookPageFactory(Context context, int w, int h,String sex,String style,String bookName) {
		mWidth = w;
		mHeight = h;
		mContext = context;
		int fontSize = Utils.getSettingsparamsByInt(context, "fontsize");
		if(mHeight>480){
			switch (fontSize) {
			case -1:
				m_fontSize = 30 ;
				marginWidth = 25 ;
				marginHeight = 32;
				break;
			case 1:
				m_fontSize = 45 ;
				marginWidth = 20 ;
				marginHeight = 32;
				break;
			case 2:
				m_fontSize = 40 ;
				marginWidth = 20 ;
				marginHeight = 32;
				break;
			case 3:
				m_fontSize = 30 ;
				marginWidth = 25 ;
				marginHeight = 32;
				break;
			case 4:
				m_fontSize = 25 ;
				marginWidth = 15 ;
				marginHeight = 24;
				break;
			default:
				break;
			}
			line = 4;
		}else{
			switch (fontSize) {
			case -1:
				m_fontSize = 18 ;
				marginWidth = 13 ;
				marginHeight = 22;
				break;
			case 1:
				m_fontSize = 25;
				marginWidth = 20 ;
				marginHeight = 24;
				break;
			case 2:
				m_fontSize = 22;
				marginWidth = 20 ;
				marginHeight = 22;
				break;
			case 3:
				m_fontSize = 18 ;
				marginWidth = 13 ;
				marginHeight = 22;
				break;
			case 4:
				m_fontSize = 15 ;
				marginWidth = 15 ;
				marginHeight = 22;
				break;
			default:
				break;
			}
			line = 2;
		}
		int fontColor = Utils.getSettingsparamsByInt(context, "fontColor");
		if (fontColor == -1)
			fontColor = Color.parseColor("black");
		int backgroundColor = Utils.getSettingsparamsByInt(context, "backgroundColor");
		if (backgroundColor == -1)
			backgroundColor = Color.parseColor("#E6D5AB");
		this.m_backColor = backgroundColor;
		
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setTextAlign(Align.LEFT);
		mPaint.setTextSize(m_fontSize);
		mPaint.setColor(fontColor);
		mVisibleWidth = mWidth - marginWidth * 2;
		mVisibleHeight = mHeight - marginHeight * 2;
		mLineCount = (int) (mVisibleHeight / (m_fontSize + line)); 
		
		this.msex = sex;
		this.mstyle = style;
		this.mbookName = bookName;
	}

	public void openbook(String sb) throws IOException {
		m_mbBufBegin = 0;
		m_lines.clear();
		lists.clear();
		lists = getPageContentStringInfo(mPaint,sb.toString(),mLineCount,mVisibleWidth);
		m_mbBufLen = lists.size();
		ReadBookActivity.msg = null;
		new Thread(this).start();
	}


	private  ArrayList<ArrayList<String>> getPageContentStringInfo(Paint m_paint, String content, int pageLines, float pageWidth) {

		char ch;
		int w = 0;
		int istart = 0;
		int lineNum = 0;
		ArrayList<ArrayList<String>> contentList = new ArrayList<ArrayList<String>>();
		ArrayList<String> cl = null;
		for (int i = 0; i < content.length(); i++) {
			if (cl == null)
				cl = new ArrayList<String>();
			ch = content.charAt(i);
			float[] widths = new float[1];
			String srt = String.valueOf(ch);
			m_paint.getTextWidths(srt, widths);
			if (ch==32||ch==9||ch==0||ch==13||ch==12288) {
				lineNum++;
				cl.add(content.substring(istart, i));
				istart = i + 1;
				w = 0;
			}

			else {
				w += (int) (Math.ceil(widths[0]));
				if (w > pageWidth) {
					lineNum++;
					cl.add(content.substring(istart, i));
					istart = i;
					i--;
					w = 0;
				} else {
					if (i == (content.length() - 1)) {
						lineNum++;
						cl.add(content.substring(istart, content.length()));
					}
				}
			}
			if (lineNum == pageLines || i == (content.length() - 1)) {
				contentList.add(cl);
				//System.out.println(cl.toString());
				cl = null;
				//lines = lineNum;
				lineNum = 0;
			}
		}
		return contentList;
	}

	protected List<String> pageDown() {
		List<String> list = new ArrayList<String>(); 
		if(lists!=null && m_mbBufBegin < lists.size())
		list = lists.get(m_mbBufBegin);
		return list;
	}

	public void prePage() throws IOException {
		if (m_mbBufBegin <= 0) {
			m_mbBufBegin = 0;
			m_isfirstPage = true;
			return;
		} else
			m_isfirstPage = false;
		//m_lines.clear();
		m_mbBufBegin--;
		m_lines = pageDown();
	}

	public void nextPage() throws IOException {
		if (m_mbBufBegin+1 >= m_mbBufLen) {
			m_islastPage = true;
			return;
		} else
			m_islastPage = false;
		//m_lines.clear();
		m_mbBufBegin++;
		m_lines = pageDown();
	}

	public void onDraw(Canvas c) {
		if (m_lines.size() == 0)
			m_lines = pageDown();
		if (m_lines.size() > 0) {
			if (m_book_bg == null)
//				c.drawColor(Color.parseColor("#E6D5AB"));
				c.drawColor(m_backColor);
			else 
				c.drawBitmap(m_book_bg, 0, 0, null);
			int y = marginHeight;
			for (String strLine : m_lines) {
				y += m_fontSize+line;
				c.drawText(strLine, marginWidth, y, mPaint);
			}
		}
		float fPercent = (float) (m_mbBufBegin * 1.0 / m_mbBufLen);
		DecimalFormat df = new DecimalFormat("#0.0");
		String strPercent = df.format(fPercent * 100) + "%";
		Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setTextAlign(Align.LEFT);
		mPaint.setTextSize(m_fontSize-5);
		mPaint.setColor(m_textColor);
		int nPercentWidth = (int) mPaint.measureText("999.9%") + 1;
		c.drawText(strPercent, mWidth - nPercentWidth, mHeight - 5, mPaint);
		
	}

	public void setBgBitmap(Bitmap BG) {
		m_book_bg = BG;
	}

	public boolean isfirstPage() {
		return m_isfirstPage;
	}

	public boolean islastPage() {
		return m_islastPage;
	}

	
	public void run() {
		if (ReadBookActivity.msg == null || "".equals(ReadBookActivity.msg)) {
			System.gc();
			if(Config.pagelists!=null &&Config.pagelists.length > Config.pageNo+1 ){
				Config.nowPage = Config.pagelists[Config.pageNo + 1];
				String url = Config.RequestUri + "sex=" + msex + "&style=" + Uri.encode(mstyle) + "&bookName=" + Uri.encode(mbookName) + "&pageCount="
						+ Uri.encode(Config.nowPage);
				
				String result =  HttpTool.getString(mContext, url);
				if(!TextUtils.isEmpty(result)){
					result = result.replace("(光影之间团队分享", "");
					result = result.replace("更多精彩内容请访问", "");
					result = result.replace("http://www.newperl.com)", "");
					ReadBookActivity.msg = result;
				}
				
			}

		}
	}
}
